package com.ylr.blog.common.algorithm;

import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-06-06 11:48:05
 * className: BlogCodeTableHintShardingAlgorithm 分表算法类
 * version: 1.0
 * description:
 */
public class BlogCodeTableHintShardingAlgorithm implements HintShardingAlgorithm<String> {

    private static final Logger log = LoggerFactory.getLogger(BlogCodeTableHintShardingAlgorithm.class);

    @Override
    public Collection<String> doSharding(Collection<String> collection, HintShardingValue<String> hintShardingValue) {
//        log.info("table => collection={}", collection);
//        log.info("table => hintShardingValue={}", hintShardingValue);
        StringBuilder sb = new StringBuilder(hintShardingValue.getLogicTableName());
        int start = hintShardingValue.getLogicTableName().length();
        return hintShardingValue.getValues()
                .stream()
                .map(code -> {
                    String blogIdSuffix = code.substring(6, 8);
                    int blogId = Integer.parseInt(blogIdSuffix);
                    String suffix = String.valueOf(blogId % 2);
                    sb.replace(start, start + suffix.length(), suffix);
                    return sb.toString();
                })
                .filter(collection::contains)
                .collect(Collectors.toSet());
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return "HINT";
    }
}
